<template>
  <div class="container">
    <div class="headerBox parentBox">
      <div class="header">
        <!--        <span class="el-dropdown-link" v-text="selectedLanguage"></span>-->
        <div class="wallet">
          <div class="wallet_body">
            <img :src="wallet" alt="wallet" />
            <div class="walletText">{{ maskString(address) }}</div>
          </div>
        </div>
        <van-dropdown-menu auto-locate>
          <van-dropdown-item v-model="value" :options="option" @change="changeLang(value)" />
        </van-dropdown-menu>
      </div>

      <!--    卖出-->
      <div class="main">
        <div class="title">
          <div class="title_text">{{ t("global.Sell") }}</div>
          <van-image class="iconHover" width="28" height="24" :src="history" @click="showPopup('history')" />
        </div>
        <div class="content sell_content">
          <div class="top">
            <div class="leftBox box">
              <div class="icon">
                <van-image width="30" height="30" :src="usdt1" />
              </div>
              <div class="token">
                <div class="text">
                  {{ sellTokenItem ? sellTokenItem.name : "" }}
                </div>
                <!-- <div class="select" @click="showPopup('token', 'sell')"> -->
                <div class="select">
                  <div class="selectText">
                    {{ sellTokenItem ? sellTokenItem.symbol : "" }}
                  </div>
                  <!-- <div class="angle"></div> -->
                </div>
              </div>
            </div>
            <div class="rightBox box">
              <div class="token">
                <div class="text">{{ sellItem ? sellItem.chainName : "" }}</div>
                <div class="select" @click="showPopup('network', 'sell')">
                  <div class="selectText">
                    {{ sellItem ? sellItem.chainName : "" }}
                  </div>
                  <div class="angle"></div>
                </div>
              </div>
            </div>
          </div>
          <div class="line"></div>
          <div class="bottom">
            <div class="bot_top">
              <van-field
                class="balance"
                style="width: 100%; height: 45px; border: none; font-size: 14px;"
                v-model.number="inpBalance"
                :placeholder="t('global.EnterMoney') + rate + ')'"
                :border="false"
                :z-index="5"
                @input.lazy="onInput"
                @blur="checkEnterMoney"
              />
            </div>
            <div class="bot_bottom">{{ t("global.Balance") }}：{{ balance }}</div>
          </div>
        </div>
      </div>
    </div>
    <div class="centerImg">
      <div class="item">
        <van-image :src="centerImg" />
      </div>
    </div>
    <div class="footerBox parentBox">
      <!--    买入 -->
      <div class="main" style="margin-top: -40px">
        <div class="title">
          <div class="title_text">{{ t("global.Buy") }}</div>
        </div>
        <div class="content buy_content">
          <div class="top">
            <div class="leftBox box">
              <div class="icon">
                <van-image width="30" height="30" :src="usdt1" />
              </div>
              <div class="token">
                <div class="text">
                  {{ buyTokenItem ? buyTokenItem.name : "" }}
                </div>
                <!-- <div class="select" @click="showPopup('token', 'buy')"> -->
                <div class="select">
                  <div class="selectText">
                    {{ buyTokenItem ? buyTokenItem.symbol : "" }}
                  </div>
                  <!-- <div class="angle"></div> -->
                </div>
              </div>
            </div>
            <div class="rightBox box">
              <div class="token">
                <div class="text">{{ buyItem ? buyItem.chainName : "" }}</div>
                <div class="select" @click="showPopup('network', 'buy')">
                  <div class="selectText">
                    {{ buyItem ? buyItem.chainName : "" }}
                  </div>
                  <div class="angle"></div>
                </div>
              </div>
            </div>
          </div>
          <div class="line"></div>

          <div class="bottom">
            <div class="bot_top">
              <div class="balance">{{ inpBalance }}</div>
            </div>
          </div>
        </div>
      </div>

      <!--    收到-->
      <div class="collection">
        <div class="willColl collBox">
          <div class="collText">{{ t("global.WillReceive") }}</div>
          <div class="collContent">{{ bugValue }}</div>
        </div>
        <div class="collAddress collBox">
          <div class="collText">{{ t("global.ReceiptAddress") }}</div>
          <div class="collContent">
            <div class="address">{{ maskString(setAddress) }}</div>
            <div class="editIcon">
              <van-icon name="edit" @click="showPopup('address')" />
            </div>
          </div>
        </div>
      </div>
    </div>

    <!--    按钮-->
    <div class="submit" @click="onSubmit">
      <span>{{ t("global.Exchange") }}</span>
    </div>
  </div>

  <!--   选择币种/链 popup  原角弹窗(底部)-->
  <van-popup v-model:show="showBottom" position="bottom" round closeable close-icon="close" :style="popupStyle">
    <div class="popHeader">
      <div class="popTitle">
        {{ popTitle }}
        <span v-if="netOrtok === 'Token'">BNB CHAIN NETWORK</span>
      </div>
      <van-field style="width: 100%; height: 3rem;display: flex; flex-direction:row; justify-content: center; align-items:center;" :border="false" v-model="queryValue" right-icon="Search" placeholder="搜索" @input="onInput" v-if="netOrtok === 'token' || netOrtok === 'network'">
        <template #button>
          <img :src="Search" alt="" class="custom-search-icon" />
        </template>
      </van-field>
    </div>
    <!--    切换网络-->
    <div class="network content" v-if="netOrtok === 'network'">
      <div class="netBody body" v-for="(item, key) in chainList" :key="key" @click="selectedNetwork(item)">
        <div class="netBody_left body_left">
          <div class="name">{{ item.chainName }}</div>
          <div class="symbol">{{ item.chainName }}</div>
        </div>
        <div class="netBody_right body_right">
          <img src="@/assets/img/USDT.png" alt="" />
        </div>
      </div>
    </div>

    <!--    切换代币-->
    <div class="token content" v-if="netOrtok === 'token'">
      <div class="tokenBody body" v-for="(item, key) in buyOrSell === 'buy' ? tokenList1 : tokenList0" :key="key" @click="selectedToken(item)">
        <div class="tokenBody_left body_left">
          <div class="iconNameBox">
            <div class="icon">
              <img src="@/assets/img/USDT.png" alt="" />
            </div>
            <div class="nameBox">
              <div class="name">{{ item.chainName }}</div>
              <div class="symbol">888</div>
            </div>
          </div>
        </div>
        <div class="tokenBody_right body_right">
          <!-- <div class="num">{{ item.num }}</div>
          <div class="amount">$ {{ item.amount.toFixed(2) }}</div> -->
        </div>
      </div>
    </div>

    <!--    历史兑换-->
    <div class="historyBody" v-if="netOrtok === 'history'">
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <van-list v-model:loading="loading" :finished="finished" :finished-text="t('global.isAll')" @load="getHistoryList">
          <div class="historyBox" v-for="(item, key) in historyList" :key="key">
            <div class="date">{{ item.timeStamp }}</div>
            <div class="body">
              <div class="left">
                <div class="top info">
                  <img class="usdtIcon" src="@/assets/img/USDT.png" alt="" />
                  <div class="text">
                    {{ `${item.amount0} ${item.tokenName0}  --  ${item.chainName0}` }}
                  </div>
                </div>
                <div class="center">
                  <img src="@/assets/img/arrow.png" alt="" />
                </div>
                <div class="bottom info">
                  <img class="usdtIcon" src="@/assets/img/USDT.png" alt="" />
                  <div class="text">
                    {{ `${item.amount1} ${item.tokenName1}  --  ${item.chainName1}` }}
                  </div>
                </div>
              </div>
              <div class="right">
                <van-loading type="spinner" size="24" v-if="item.status == 0" />
                <img src="@/assets/img/success.png" alt="" v-else-if="item.status == 1" />
                <van-icon name="clear" size="24" color="#e6a23c" v-else />
              </div>
            </div>
          </div>
        </van-list>
      </van-pull-refresh>
    </div>

    <!--    设置收款地址-->
    <div class="addressBox" v-if="netOrtok === 'address'">
      <van-field style="width: 100%; height: 45px; border: none" v-model="setAddress" :placeholder="t('global.EnterAddress')" :border="false" :z-index="5" @input="onInput" />
      <p @click="useCurrentAddress">{{ t("global.UseCurrentAddress") }}</p>
      <div class="btns">
        <div class="btn cancel" @click="cancelSetAddress">
          {{ t("global.Cancel") }}
        </div>
        <div class="btn confirm" @click="confirm">
          {{ t("global.Confirm") }}
        </div>
      </div>
    </div>
  </van-popup>
</template>

<script setup>
import { computed, ref, watch, unref, onMounted } from "vue";
import history from "@/assets/img/history.png";
import Search from "@/assets/img/search.png";
import centerImg from "@/assets/img/centerImg.png";
import usdt1 from "@/assets/img/USDT1.png";
import wallet from "@/assets/img/wallet.png";
import { useUserStore } from "@/stores";
import { showNotify, showLoadingToast, closeToast, showToast } from "vant";
import { connectWallet, transfer, balanceOf } from "@/utils/utils.js";
import { createChainApply, getChainApplyList, getChainList, getChainTokenList, getRate } from "@/require/api.js"; // 提交兑换申请

import { useI18n } from "vue-i18n"; // 导入 i18n 模块，国际化
const { t } = useI18n();

// 监听ethereum的accountsChanged事件。当账户列表发生变化时，如果账户数量大于0，则调用init函数初始化。
window.ethereum.on("accountsChanged", async (accounts) => {
  if (accounts.length > 0) {
    await init();
  }
});

// onMounted(() => init());
onMounted(async () => {
  await pageInit();
  await init();
});

const userStore = useUserStore();
const { locale } = useI18n();

watch(
  () => userStore.getLocale,
  (newVal) => {
    locale.value = newVal;
  },
  { immediate: true }
);


// 将收到 的 usdt
const bugValue = computed(() => {

  // return (unref(inpBalance) * unref(rate)).toFixed(2);

  // 逻辑变更: 您将收到的值 由 输入值 * 利率   改为 输入值 - 1 并且 输入值至少要大于1
  if(inpBalance.value < rate.value){
    return '0.00'
  }

  const balanceVal = parseFloat(inpBalance.value)
  if(!isNaN(balanceVal)){
    return  (unref(Number(balanceVal - unref(rate)))).toFixed(2);
  }
  return '0.00'
}); // 买入 和 您将收到的 值
const balance = ref(""); // 余额
const inpBalance = ref(""); // 输入的值 余额
const address = ref(""); // 收款地址
const setAddress = ref(""); // 设置收款地址
const showBottom = ref(false); // 选择币种/链 popup
const netOrtok = ref(""); // 点击按钮类型 network / token
const buyOrSell = ref("sell"); // 买 还是 卖
const popTitle = ref(""); // popup标题
const queryValue = ref(""); // popup 搜索框绑定值
const status = ref(Number(1)); // 兑换状态  0:兑换中 1:兑换成功 2:用户过期 3:兑换失败
const inpAddress = ref(""); // 设置收款地址
const maxNumber = ref(0); // 最大可兑换金额
const value = ref(0); // 选择语言
const option = [
  { text: "繁體中文", value: 0 },
  { text: "简体中文", value: 1 },
  { text: "English", value: 2 },
  { text: "한문", value: 3 },
  { text: "日本語", value: 4 },
];

// 获取链列表
async function chainListFun() {
  try {
    // 668f9383b5e9fc0dd6ade849
    const { code, data, msg } = await getChainList();
    if (code === 200) {
      chainList.value = data;
      sellItem.value = data[0];
      buyItem.value = data[1];
    } else {
      console.log(msg);
    }
  } catch (e) {
    console.log(e);
  }
}

// 获取tokenList
async function chainTokenListFun(chainConfigId) {
  const { code, data, msg } = await getChainTokenList({chainConfigId});
  if (code === 200) {
    tokenList.value = data;
  } else {
    console.log(msg);
  }
}

const rate = ref(1);
// 获取利率
async function rateFun() {
  try {
    const { code, data, msg } = await getRate({
      chainConfigId0: unref(sellItem).chainConfigId,
      chainConfigId1: unref(buyItem).chainConfigId,
      token0: unref(sellTokenItem).id,
      token1: unref(buyTokenItem).id,
    });
    if (code === 200) {
      rate.value = data.rate;
      maxNumber.value = data.maxNumber;
    }
  } catch (e) {
    console.log(e);
  }
}

const chainList = ref([]); // 链列表
const tokenList = ref([]); // token 列标配

const sellItem = ref();
const buyItem = ref();
const buyTokenItem = ref();
const sellTokenItem = ref();

const historyList = ref([]);

// 修改样式
const popupStyle = computed(() => {
  let height = "80%";
  if (netOrtok.value === "Token" || netOrtok.value === "Network") {
    height = "80%"; // 根据需要调整高度
  } else if (netOrtok.value === "History") {
    height = "70%"; // 根据需要调整高度
  } else if (netOrtok.value === "address") {
    height = "40%"; // 根据需要调整高度
  }
  return {
    height: height,
    padding: "0 20px",
    background: "#2F2665",
    overflowY: "hidden",
  };
});

async function init() {
  // alert("请安装MetaMask");
  address.value = await connectWallet(unref(sellItem).chainId);
  setAddress.value = unref(address);
  balance.value = await balanceOf(unref(sellTokenItem).address, unref(address));
}

async function pageInit() {
  await chainListFun(); //获取链列表
  await chainTokenListFun(sellItem.value.chainConfigId);
  sellTokenItem.value = unref(tokenList)[0];
  await chainTokenListFun(buyItem.value.chainConfigId);
  buyTokenItem.value = unref(tokenList)[0];
  await rateFun();
}

// 选择币种/链 popup 方法
async function showPopup(type, buySell) {
  try {
    showBottom.value = true;
    netOrtok.value = type;
    buyOrSell.value = buySell;
    if (type === "token") {
      return (popTitle.value = "Token");
    } else if (type === "network") {
      return (popTitle.value = "Network");
    } else if (type === "history") {
      historyList.value = [];
      pageIndex.value = 1;
      // getHistoryList()
      popTitle.value = t("global.HistoryExchange");
    } else if (type === "address") {
      return (popTitle.value = t("global.SetCollectionAddress"));
    }
  } catch (e) {
    console.log(e);
  }
}

// 获取历史数据
const pageIndex = ref(1);
const pageSize = ref(10);
const loading = ref(false);
const finished = ref(false);
const refreshing = ref(false); // 下拉刷新

function getHistoryList() {
  setTimeout(async () => {
    if (refreshing.value) {
      pageIndex.value = 1;
      historyList.value = [];
      refreshing.value = false;
    }

    const { code, data, msg } = await getChainApplyList({
      pageIndex: unref(pageIndex),
      pageSize: unref(pageSize),
      from: unref(address),
    });
    if (code === 200) {
      pageIndex.value++;
      historyList.value = data.list == null ? [...unref(historyList)] : [...historyList.value, ...data.list];
    }

    loading.value = false;

    if (historyList.value.length >= data.total) {
      finished.value = true;
    }
  }, 100);
}

// 下拉加载
function onRefresh() {
  // 清空列表数据
  finished.value = false;
  loading.value = true;
  getHistoryList();
}

// 取消 设置收款地址
function cancelSetAddress() {
  showBottom.value = false;
  inpAddress.value = "";
}

// 确认收款地址方法
function confirm() {
  showBottom.value = false;
}
// 兑换方法
async function onSubmit() {
  try {
    if (unref(inpBalance) == "") {
      showNotify({
        message: t("global.AmountErr"),
        color: "#ffffff",
        background: "#f56c6c",
      });
      return;
    }

    if (unref(setAddress) == "") {
      showNotify({
        message: t("global.EnterCollectionAddress"),
        color: "#ffffff",
        background: "#f56c6c",
      });
      return;
    }

    if (inpBalance.value <= rate.value) {
      showNotify({
        message: t("global.EnterMoney1") + rate.value,
        color: "#ffffff",
        background: "#f56c6c",
      });
      return;
    }

    if (unref(sellItem).chainConfigId === unref(buyItem).chainConfigId) {
      showNotify({
        message: t("global.Redeem"),
        color: "#ffffff",
        background: "#f56c6c",
      });
      return;
    }



    showLoadingToast({
      duration: 0,
      message: "Loading...",
      forbidClick: true,
    });
    const token = unref(sellTokenItem).address;
    const toAddr = unref(sellItem).collectAddress;
    const amount = unref(inpBalance);
    const tx = await transfer(token, toAddr, amount);

    if (!tx) {
      showNotify({
        message: t("global.Error"),
        color: "#ffffff",
        background: "#f56c6c",
      });
      return;
    }
    const { code, msg } = await createChainApply({
      chainConfigId0: unref(sellItem).chainConfigId,
      chainConfigId1: unref(buyItem).chainConfigId,
      tokenId0: unref(sellTokenItem).id,
      tokenId1: unref(buyTokenItem).id,
      txHash: tx,
      from: unref(address),
      to: unref(setAddress),
      amount0: amount.toString(),
      amount1: amount.toString(),
    });
    if (code === 200) {
      showNotify({
        message: t("global.Submit"),
        color: "#ffffff",
        background: "#67c23a",
      });
    }else{
      console.log(msg);
    }
  } catch (error) {
    console.error(error);
  } finally {
    inpBalance.value = '';
    closeToast();
  }
}

// popup输入事件
function onInput(v) {
  // 如果inpBalance.value > balance.value 则把 balance.value 赋值给  inpBalance.value,并且无法继续输入
  if (inpBalance.value > balance.value) {
    inpBalance.value = balance.value;
  }
  // bugValue.value = inpBalance.value;
}


// 输入值必须大于 rate
function checkEnterMoney(v) {
  if(parseFloat(inpBalance.value) <= rate.value){
    showNotify({
      message: t("global.EnterMoney1") + rate.value,
      color: "#ffffff",
      background: "#ff976a",
    });
    return;
  }

  // 最大兑换金额
  if(maxNumber.value != 0 && parseFloat(inpBalance.value) >= maxNumber.value  ){
    showNotify({
      message: t("global.cantMax") + ":" + maxNumber.value,
      color: "#ffffff",
      background: "#ff976a",
    });
    return;
  }
}

// 使用当前收款地址
function useCurrentAddress() {
  setAddress.value = address.value;
  showBottom.value = false;
}

// 字符串 处理
function maskString(s) {
  if (!s || s.length <= 8) {
    return s; // 如果字符串长度小于等于8，直接返回原字符串
  } else if (s) {
    const prefix = s.slice(0, 4);
    const suffix = s.slice(-4);
    return prefix + "****" + suffix;
  }
}

function selectedToken(item) {
  if (buyOrSell.value === "sell") {
    sellTokenItem.value = item;
    showBottom.value = false;
  } else if (buyOrSell.value === "buy") {
    buyTokenItem.value = item;
  }
}

async function selectedNetwork(item) {
  await chainTokenListFun(item.chainConfigId);
  if (buyOrSell.value === "sell") {
    sellItem.value = item;
    sellTokenItem.value = unref(tokenList)[0];
    // 我直接调用了初始化 正常流程是切换完网络 根据当前的id去调用接口获取token列表 然后默认选中第一个token后 在调用初始化
    showToast({
      message: t("global.SwitchNetwork"),
      duration: 1000,
      onClose: () => init(),
    });
  } else if (buyOrSell.value === "buy") {
    buyItem.value = item;
    buyTokenItem.value = unref(tokenList)[0];
  }
  showBottom.value = false;
  rateFun(); //获取利率
}

// 切换语言的方法
function changeLang(value) {
  const langMap = {
    0: "zh-TW",
    1: "zh-CN",
    2: "en-US",
    3: "ko-KR",
    4: "ja-JP",
  };
  handleToggleLocale(langMap[value]);
}

// 切换语言的方法
function handleToggleLocale(value) {
  userStore.setLocale(value);
  // window.location.reload();
}
</script>

<style scoped lang="less">
@import url("./style.less");
</style>
